<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card style="margin-bottom: 10px">

          距离考试结束还有：
          <exam-timer v-model="paperData.leftSeconds" @timeout="timeOut" />

          <el-button style="float: right; margin-top: -10px" type="primary" icon="el-icon-plus" :loading="loading"
            @click="handHandExam()">
            {{ handleText }}
          </el-button>

        </el-card>
      </el-col>
      <el-col :span="6" :xs="24" style="margin-bottom: 10px">

        <el-card>
          <p class="card-title">答题卡</p>
          <el-row :gutter="24" class="card-line" style="padding-left: 10px">
            <el-tag type="info">未作答</el-tag>
            <el-tag type="success">已作答</el-tag>
          </el-row>

          <div>
            <p class="card-title">单选题(40分)</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.radioList" :key="item.id" :type="cardItemClass(item.answered, item.id)"
                @click="handSave(item)"> {{ item.sort }}
              </el-tag>
            </el-row>
          </div>

          <div>
            <p class="card-title">多选题(60分)</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.multiList" :key="item.id" :type="cardItemClass(item.answered, item.id)"
                @click="handSave(item)">{{ item.sort }}
              </el-tag>
            </el-row>
          </div>

        </el-card>

      </el-col>
      <el-col :span="18" :xs="24">

        <el-card class="qu-content">
          <p v-if="quData.testName">{{ quData.sort }}.{{ quData.testName }}</p>
          <div v-if="quData.isMultilychoice === 2">
            <el-radio-group v-model="radioValue">
              <el-radio v-for="item in quData.examOption" :key="item.id" :label="item.id">{{ item.optiones }}
              </el-radio>
            </el-radio-group>
          </div>
          <div v-if="quData.isMultilychoice === 1">

            <el-checkbox-group v-model="multiValue">
              <el-checkbox v-for="item in quData.examOption" :key="item.id" :label="item.id">{{ item.optiones }}

              </el-checkbox>
            </el-checkbox-group>

          </div>

        </el-card>

        <div style="margin-top: 20px">
          <el-button v-if="showPrevious" type="primary" icon="el-icon-back" @click="handPrevious()">
            上一题
          </el-button>

          <el-button v-if="showNext" type="warning" icon="el-icon-right" @click="handNext()">
            下一题
          </el-button>

        </div>

      </el-col>
    </el-row>
  </div>
</template>

<script>
  import ExamTimer from "../../components/ExamTimer";

  export default {
    name: "exam",
    data() {
      return {
        //题目页
        index: 0,
        //是否有上一题，下一题
        showPrevious: false,
        showNext: true,
        loading: false,
        handleText: '交卷',
        // 单选选定值
        radioValue: '',
        // 多选选定值
        multiValue: [],
        //
        paperData: {
          leftSeconds: 999,
          radioList: [],
          multiList: [],
        },
        // 当前答题卡
        cardItem: {
          testId: '',
          userTrainId: '',
          isMultilychoice: '',
          answerId: ''
        },
        allItem: [],
        // 当前题目内容
        quData: {},
        examPaper: [],
        //后端传参
        examAnswer: {
          trainId: '',
          answerArray: []
        }
      }
    },
    created() {
      console.log(this.$route);
      this.examAnswer.trainId = this.$route.params.tarinId;
      this.getData()
    },
    //注册组件
    components: {
      ExamTimer
    },
    methods: {
      getData() {
        this.$axios.get('/api/test/findExam/' + this.examAnswer.trainId).then(res => {
          console.log(res)
          if (res.data.code === 200) {
            this.initExam(res)
          } else {
            this.$alert(res.data.message, '提示', {
              confirmButtonText: '确定',
              callback: action => {
                //跳转到查看培训状态页面
                let user = JSON.parse(localStorage.getItem("userdata"))

                //跳转到个人主页
                this.$router.push({
                  path: '/userTrain/userTrainMessage/',
                  query: {
                    "userid": user.id
                  }
                })
              }
            });
          }
        }).catch(e => {
          console.log(e);
        })
      },
      //初始化数据
      initExam(res) {
        this.examPaper = res.data.data
        for (let i = 0; i < this.examPaper.length; i++) {
          if (this.examPaper[i].isMultilychoice === 2) {
            this.paperData.radioList.push(this.examPaper[i])
          } else {
            this.paperData.multiList.push(this.examPaper[i])
          }
        }
        this.quData = this.examPaper[this.index];
      },
      //答题卡样式
      cardItemClass(answered, quId) {
        if (quId === this.cardItem.quId) {
          return 'warning'
        }

        if (answered) {
          return 'success'
        }

        if (!answered) {
          return 'info'
        }
      },
      timeOut() {
        this.submitAnswer(this.allItem)
      },
      // 交卷操作
      handHandExam() {
        this.handSave();
        const notAnswered = this.countNotAnswered()

        let msg = '确认要交卷吗？'

        if (notAnswered > 0) {
          msg = '您还有' + notAnswered + '题未作答，确认要交卷吗?'
        }

        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitAnswer(this.allItem)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '交卷已取消，您可以继续作答！'
          })
        })
      },
      //渲染题目保存答案
      handSave(item) {
        console.log(item)
        if (item != undefined && item != 'undefined') {
          this.saveAnswer(item)
          this.answerEcho(item)
          this.quData = item
          this.index = item.sort - 1
        } else {
          this.saveAnswer()
          this.quData = this.examPaper[this.index]
          this.answerEcho(this.quData)
          console.log(this.allItem)
        }

        if (this.index === this.examPaper.length - 1 || this.index > this.examPaper.length) {
          this.showNext = false
        } else {
          this.showNext = true
        }
        if (this.index > 0) {
          this.showPrevious = true
        } else {
          this.showPrevious = false
        }

      },
      /**
       * 上一题
       */
      handPrevious() {
        this.index--
        this.handSave()
      },
      //下一题
      handNext() {
        this.index++
        this.handSave()
      },

      saveAnswer(item) {
        if (this.quData.answered == true) {
          this.alertAnswer(item)
        } else {
          if (this.radioValue !== '' || this.multiValue.length > 0) {
            if (this.quData.isMultilychoice === 1) {
              this.allItem.push({
                testId: this.quData.id,
                userTrainId: this.quData.userTrainId,
                isMultilychoice: 1,
                answerId: this.multiValue.toString()
              })
              this.radioValue = ''
              this.multiValue.length = []
            } else {
              this.allItem.push({
                testId: this.quData.id,
                userTrainId: this.quData.userTrainId,
                isMultilychoice: 2,
                answerId: this.radioValue
              })
              this.radioValue = ''
              this.multiValue.length = []
            }
            this.examPaper[this.quData.sort - 1].answered = true
          }
        }

      },
      //回显答案
      answerEcho(item) {
        for (let allItemElement of this.allItem) {
          if (allItemElement.testId === item.id) {
            if (allItemElement.isMultilychoice === 1) {
              let arr = allItemElement.answerId.split(',')
              this.multiValue = arr.map(i => parseInt(i, 0))
            } else {
              this.radioValue = allItemElement.answerId
            }
            break
          }
        }
      },
      //修改方法
      alertAnswer() {
        let allItemElement = null;
        for (allItemElement of this.allItem) {
          if (allItemElement.testId === this.quData.id) {
            if (allItemElement.isMultilychoice === 1) {
              allItemElement.answerId = this.multiValue.toString()
              break;
            } else {
              allItemElement.answerId = this.radioValue
              break;
            }
          }
        }
        if (allItemElement.answerId == '') {
          this.examPaper[this.quData.sort - 1].answered = false
          for (let i = 0; i < this.allItem.length; i++) {
            if (allItemElement.testId == this.allItem[i].testId) {
              this.allItem.splice(i, 1)
              break;
            }
          }

        }

        this.radioValue = ''
        this.multiValue.length = []
      },
      /**
       * 统计有多少题没答的
       * @returns {number}
       */
      countNotAnswered() {
        let notAnswered = 0

        this.paperData.radioList.forEach(function (item) {
          if (!item.answered) {
            notAnswered += 1
          }
        })

        this.paperData.multiList.forEach(function (item) {
          if (!item.answered) {
            notAnswered += 1
          }
        })
        return notAnswered
      },
      submitAnswer(answerArray) {
        this.examAnswer.answerArray = answerArray
        console.log(this.examAnswer)
        this.$axios.post('/api/test/submitAnswer/', this.examAnswer).then(res => {
          console.log(res)
          if (res.data.code === 200) {
            this.$alert(res.data.data, '考试结果', {
              confirmButtonText: '确定',
              callback: action => {
                //跳转到查看培训状态页面
                let user = JSON.parse(localStorage.getItem("userdata"))

                //跳转到个人主页
                this.$router.push({
                  path: '/userTrain/userTrainMessage/',
                  query: {
                    "userid": user.id
                  }
                })
              }
            });
          } else {
            this.$alert(res.data.data, '考试结果', {
              confirmButtonText: '确定',
              callback: action => {
                //跳转到查看培训状态页面

                let user = JSON.parse(localStorage.getItem("userdata"))

                //跳转到个人主页
                this.$router.push({
                  path: '/userTrain/userTrainMessage/',
                  query: {
                    "userid": user.id
                  }
                })
              }
            });
          }
        })
      }
    }


  }

</script>

<style scoped>
  .qu-content div {
    line-height: 30px;
  }

  .el-checkbox-group label,
  .el-radio-group label {
    width: 100%;
  }

  .card-title {
    background: #eee;
    line-height: 35px;
    text-align: center;
    font-size: 14px;
  }

  .card-line {
    padding-left: 10px
  }

  .card-line span {
    cursor: pointer;
    margin: 2px;
  }

   .el-radio,
  .el-checkbox {
    padding: 9px 20px 9px 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-bottom: 10px;
  }

  .is-checked {
    border: #409eff 1px solid;
  }

  .el-radio img,
  .el-checkbox img {
    max-width: 200px;
    max-height: 200px;
    border: #dcdfe6 1px dotted;
  }

   .el-checkbox__inner {
    display: none;
  }

   .el-radio__inner {
    display: none;
  }

   .el-checkbox__label {
    line-height: 30px;
  }

   .el-radio__label {
    line-height: 30px;
  }

</style>
